package org.novelhibernate.support.logging;

import java.util.HashMap;
import java.util.Map;

import org.novelhibernate.exception.NovelhibernateException;

public class NativeLogFactory extends LogFactorySupport {

	static {

		factory = new NativeLogFactory();
	}

	private static NativeLogFactory factory;

	private Map<Class<?>, Object> registry;

	private NativeLogFactory() {

		registry = new HashMap<Class<?>, Object>();
	}

	public static NativeLogFactory getInstance() {

		return factory;
	}

	public synchronized Object produceLogPointBase(Class<?> proxy,
			boolean isUseProxy) throws InstantiationException,
			IllegalAccessException {

		Object object = null;
		// keep the proxy singleton here
		if (registry.containsKey(proxy))
			object = registry.get(proxy);
		else {
			object = new LogHandler(proxy, (isUseProxy) ? null : proxy, factory)
					.getProxy();
			registry.put(proxy, object);
		}
		return object;
	}

	public synchronized Object produceLogPointBase(Object proxy,
			Class<?> instance) throws InstantiationException,
			IllegalAccessException {

		Object object = null;
		// keep the proxy singleton here
		if (registry.containsKey(proxy.getClass()))
			object = registry.get(proxy.getClass());
		else {
			object = new LogHandler(proxy, instance, factory).getProxy();
			registry.put(proxy.getClass(), object);
		}
		return object;
	}

	public synchronized Object produceLogPointBase(Object proxy)
			throws InstantiationException, IllegalAccessException, NovelhibernateException {

		if (proxy instanceof Class)
			throw new NovelhibernateException ("Wrong arguments for logging proxy create method, except object not a class");
		
		Object object = null;
		// keep the proxy singleton here
		if (registry.containsKey(proxy.getClass()))
			object = registry.get(proxy.getClass());
		else {
			object = new LogHandler(proxy, null, factory).getProxy();
			registry.put(proxy.getClass(), object);
		}
		return object;
	}

}
